import React, {useRef} from "react";

import {
  FormFieldType,
  ProFormColumnsType
} from "@ant-design/pro-form/lib/components/SchemaForm/typing";
import {FormInstance, ProFormInstance} from "@ant-design/pro-form";
import {Button, message} from "antd";
import {PlusOutlined} from "@ant-design/icons";
import {BetaSchemaForm, ProFieldValueType} from '@ant-design/pro-components';

interface Props {
  onChange?: (event: number | string) => void;
  request?:Promise<any>;
  columns: ProFormColumnsType<any, ProFieldValueType | FormFieldType>[] | ((values: any) => ProFormColumnsType<any, ProFieldValueType | FormFieldType>[]);
  btnText: string|"";
  title: string|"";
  initialValues:any;
  width:number|null;
  formRef?: React.MutableRefObject<ProFormInstance<any> | undefined> | React.RefObject<ProFormInstance<any> | undefined>;

}

const FormModalBtn:React.FC<Props>=(props)=>{
  let {columns, request,btnText,title,initialValues,width,onChange,formRef} = props;
 if(formRef==undefined){
   formRef= useRef<FormInstance> ();
 }

  return (
      <BetaSchemaForm
        width={width!=null?width:500}
        layoutType="ModalForm"
        title={title}
        onCurrentChange={(current: any) => {
          return console.log ( 'current: ', current );
        }}
        trigger={
          <Button type="primary">
            <PlusOutlined />
            {btnText}
          </Button>
        }
        initialValues={initialValues}
        formRef={formRef}
        onFinish={ (values) => {
          return new Promise ( (resolve, reject) => {
            console.log ( values );
            if (request != null) {
              // @ts-ignore
              request( values ).then ( (res: any) => {

                console.log ("操作", res );
                let success = res.success
                if(success) {
                  message.success("操作成功")
                  if (onChange) {
                    onChange ( res )
                  }
                  resolve ( res )
                }else{
                  message.error("操作失败")
                  reject ( res )
                }
              } ).catch ( (error: any) => {
                message.error("操作失败")
                reject ( error )
              } )
            }
          } );
        }}
        columns={columns}
      />
      );

}
export default FormModalBtn;
